package com.luoxue.execsql.rest.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.luoxue.execsql.common.contact.ExecSqlContact;
import com.luoxue.execsql.common.util.ResultBody;
import com.luoxue.execsql.common.util.TableData;
import com.luoxue.execsql.rest.bean.base.controller.BaseController;
import com.luoxue.execsql.rest.entity.DynamicSql;
import com.luoxue.execsql.rest.entity.SysDataSource;
import com.luoxue.execsql.rest.mapper.DynamicSqlMapper;
import com.luoxue.execsql.rest.service.IDataSourceService;
import com.luoxue.execsql.rest.service.IDynamicSqlService;
import com.luoxue.execsql.rest.service.impl.ParameterValidationService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("/dynamicSql")
public class DynamicSqlController extends BaseController<DynamicSql, DynamicSqlMapper, IDynamicSqlService> {

    @Autowired
    private IDataSourceService dataSourceService;

    @Autowired
    private ParameterValidationService parameterValidationService;

    public DynamicSqlController(IDynamicSqlService service) {
        super(service);
    }

    @Override
    protected void queryParams(DynamicSql entity, QueryWrapper<DynamicSql> queryWrapper) {
        if (Strings.isNotBlank(entity.getSqlTag())) {
            if (entity.getSqlTag().startsWith(ExecSqlContact.refineSearch)) {
                queryWrapper.lambda().eq(DynamicSql::getSqlTag, entity.getSqlTag().substring(1));
            } else {
                queryWrapper.lambda().like(DynamicSql::getSqlTag, entity.getSqlTag());
            }
        }
        if (Strings.isNotBlank(entity.getDataSourceName())) {
            queryWrapper.lambda().eq(DynamicSql::getDataSourceName, entity.getDataSourceName());
        }
        queryWrapper.orderByDesc("update_time", "id");
    }

    @Override
    public Mono<ResultBody> getById(@PathVariable String id) {
        DynamicSql dynamicSql = service.getById(id);
        dynamicSql.setParameterValidationList(parameterValidationService.selectBySqlTag(dynamicSql.getSqlTag()));
        return Mono.just(ResultBody.ok("查询成功", dynamicSql));
    }

    @Override
    public Mono<ResultBody> save(@RequestBody DynamicSql entity) {
        parameterValidationService.saveByDynamicSql(entity);
        return super.save(entity);
    }

    @Override
    public Mono<ResultBody> updateById(@RequestBody DynamicSql entity) {
        parameterValidationService.saveByDynamicSql(entity);
        return super.updateById(entity);
    }
}
